package com.nxuer.controllers.pkg01;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.util.Arrays;

@Service
public class RealTimeDataRequester {
    String url;
    HttpGet get;
    HttpClient httpClient;
    RealTimeDataRequester() {
        url = "http://iot.0531yun.cn/wsjc/app/GetDeviceData";
        httpClient = HttpClients.createDefault();
        get = new HttpGet();
        get.setHeader("userId", "9372");
    }
    public JSONArray sendRequest(int num) {
        try {
            get.setURI(URI.create(url + "?groupId=" + num));
            System.out.println(Arrays.toString(get.getAllHeaders()));
            HttpResponse httpResponse = httpClient.execute(get);
            JSONObject jsonResponse = JSON.parseObject(EntityUtils.toString(httpResponse.getEntity()));
            if (jsonResponse.getInteger("code").equals(1000)) {
                JSONArray tmp = jsonResponse.getJSONArray("data");
                JSONArray ret = new JSONArray();
                for (int i = 0; i < tmp.size(); i++) {
                    JSONObject j  = tmp.getJSONObject(i);
                    j.remove("deviceKey");
                    j.remove("deviceAddr");
                    j.remove("nodeType");
                    j.remove("deviceDisabled");
                    j.remove("lng");
                    j.remove("lat");
                    ret.add(j);
                }
                return ret;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JSONArray();
    }
}
